package face.pay.cpn.activityInfo.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import face.pay.AbstractRedis;
import face.pay.constant.CacheKey;
import face.pay.cpn.activityInfo.ICpnActivityInfoService;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.ResultMessage;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.MediaAPI;
import weixin.popular.bean.media.UploadimgResult;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Classname CpnActivityInfoServiceImpl
 * @Description JJL
 * @Date 2019/12/2 9:41
 */
@Service
@Slf4j
public class CpnActivityInfoServiceImpl implements ICpnActivityInfoService {

    @Autowired
    private CpnActivityInfoDao cpnActivityInfoDao;

    @Autowired
    private CpnMchInfoDao cpnMchInfoDao;

    @Autowired
    private CpnMchServiceInfoDao cpnMchServiceInfoDao;

    @Autowired
    private CpnOpenMchDao cpnOpenMchDao;

    @Autowired
    private CpnCardInfoDao cpnCardInfoDao;

    @Autowired
    private StoreInfoDao storeInfoDao;

    @Autowired
    private AbstractRedis abstractRedis;

    /**
     * 获取token
     *
     * @return
     */
    private String getAccess_token() {
        String str = (String) this.abstractRedis.get(CacheKey.WX_APP_INFO);
        if (str == null) {
            return null;
        }
        CpnWxAppInfo cpnWxAppInfo = null;
        try {
            cpnWxAppInfo = JSONObject.parseObject(str, CpnWxAppInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return cpnWxAppInfo.getAccess_token();
    }

    /**
     * 分页查询活动信息
     *
     * @param activityInfo
     * @param pageParam
     * @return
     */
    @Override
    public PageData<CpnActivityInfo> queryPage(CpnActivityInfo activityInfo, PageParam pageParam) {

        PageHelper.startPage(pageParam.getPageNo(), pageParam.getPageSize());

        List<CpnActivityInfo> storeInfos = this.cpnActivityInfoDao.queryList(activityInfo);

        PageInfo<CpnActivityInfo> pageInfo = new PageInfo<>(storeInfos);

        PageData<CpnActivityInfo> pageData = new PageData<>(pageInfo.getTotal(), storeInfos);

        return pageData;
    }

    /**
     * 查询单个活动下的所有类型卡券
     *
     * @param cpnCardInfo
     * @param pageParam
     * @param userInfo
     * @return
     */
    @Override
    public PageData queryActivityCard(CpnCardInfo cpnCardInfo, PageParam pageParam, UserInfo userInfo) {
        PageHelper.startPage(pageParam.getPageNo(), pageParam.getPageSize());

        List<CpnCardInfo> storeInfos = this.cpnActivityInfoDao.queryActivityCard(cpnCardInfo);

        PageInfo<CpnCardInfo> pageInfo = new PageInfo<>(storeInfos);

        PageData<CpnCardInfo> pageData = new PageData<>(pageInfo.getTotal(), storeInfos);

        return pageData;
    }

    /**
     * 保存活动信息与修改活动信息
     *
     * @param activityInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage modifyActivityInfo(CpnActivityInfo activityInfo, UserInfo userInfo) {

        if (activityInfo.getId() == null) {  //新增
            StoreInfo storeInfo = storeInfoDao.getCardStore(userInfo.getId());
            if (storeInfo != null && storeInfo.getProvince() == null) {
                return ResultMessage.createFail("请先补充优惠券门店信息!");
            }
            activityInfo.setOemId(userInfo.getOemId());
            activityInfo.setUserId(userInfo.getId());
            activityInfo.setCreatedBy(userInfo.getId());
            //得到商户merchant_id
            CpnMchInfo cpnMchInfo = new CpnMchInfo();
            cpnMchInfo.setUserId(userInfo.getId());
            CpnMchInfo mchInfo = cpnMchInfoDao.queryCpnMchInfo(cpnMchInfo);
            if (mchInfo.getMerchant_id() == null) {
                return ResultMessage.createFail("请先进行商家进件!");
            }
            //得到商家服务费率service_fee
            CpnMchServiceInfo cpnMchServiceInfo = new CpnMchServiceInfo();
            cpnMchServiceInfo.setUserId(userInfo.getId());
            CpnMchServiceInfo mchServiceInfo = cpnMchServiceInfoDao.queryCpnMchServiceInfo(cpnMchServiceInfo);
            if (mchServiceInfo.getService_fee() == null) {
                return ResultMessage.createFail("请先配置商家服务!");
            }
            activityInfo.setMerchant_id(mchInfo.getMerchant_id());
            //添加活动 添加成功返回主键
            cpnActivityInfoDao.insert(activityInfo);
            if (activityInfo.getId() != null) {

                CpnCardInfo cpnCardInfo = new CpnCardInfo();
                cpnCardInfo.setOemId(userInfo.getOemId());
                cpnCardInfo.setUserId(userInfo.getId());
                cpnCardInfo.setMerchant_id(mchInfo.getMerchant_id());
                cpnCardInfo.setActivityId(activityInfo.getId());
                cpnCardInfo.setCreatedBy(userInfo.getId());
                cpnCardInfo.setCard_type("DISCOUNT");  //折扣券
                cpnCardInfo.setCode_type("CODE_TYPE_QRCODE"); //二维码显示
                cpnCardInfo.setType("DATE_TYPE_FIX_TERM"); //固定时长 自领取后按天算
                //活动创建后，提供五种折扣券
                List<CpnCardInfo> cpnCardInfoList = new ArrayList<>();
                for (int i = 0; i < 5; i++) {
                    CpnCardInfo cardInfo = new CpnCardInfo();
                    BeanUtils.copyProperties(cpnCardInfo, cardInfo);
                    cpnCardInfoList.add(cardInfo);
                    switch (i) {
                        case 0:
                            cardInfo.setDiscount(0.05);
                            break;
                        case 1:
                            cardInfo.setDiscount(0.10);
                            break;
                        case 2:
                            cardInfo.setDiscount(0.15);
                            break;
                        case 3:
                            cardInfo.setDiscount(0.20);
                            break;
                        case 4:
                            cardInfo.setDiscount(0.25);
                            break;
                        default:
                            break;
                    }
                }
                cpnCardInfoDao.insertDiscountCard(cpnCardInfoList);
                log.info("活动id:" + activityInfo.getId() + "成功创建5条折扣券信息");
                return ResultMessage.createSuccess();
            } else {
                return ResultMessage.createFail("添加活动失败");
            }
        } else {  //修改
            activityInfo.setUpdatedBy(userInfo.getId());
            cpnActivityInfoDao.update(activityInfo);
            return ResultMessage.createSuccess();
        }
    }

    /**
     * 封面上传
     *
     * @param fileBytes
     * @param originalFilename
     * @param loginUser
     * @param conver_text      封面摘要简介。
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage addConverText(byte[] fileBytes, String originalFilename, UserInfo loginUser, String conver_text, Integer id) {
        //   获取access_token
        String access_token = getAccess_token();
        if (access_token == null || access_token.isEmpty()) {
            log.warn("上传图片 userId:{} 获取access_token失败!!!!", loginUser.getId());
            return ResultMessage.createFail("请稍后再试!!!");
        }
        UploadimgResult result = MediaAPI.mediaUploadimg(access_token, new ByteArrayInputStream(fileBytes));
        if (result == null || StringUtils.isBlank(result.getUrl())) {
            log.warn("上传图片 userId:{} 上传失败!!!!", loginUser.getId());
            return ResultMessage.createFail("上传失败请检查文件大小,或请稍后再试!!!");
        }
        CpnActivityInfo info = new CpnActivityInfo();
        info.setId(id);
        info.setConver_text(conver_text);
        info.setIcon_url(result.getUrl());
        info.setUpdatedBy(loginUser.getId());
        this.cpnActivityInfoDao.updateConverText(info);
        HashMap<String, String> map = new HashMap<>();
        map.put("icon_url", result.getUrl());
        return ResultMessage.createSuccess(map);
    }

    /**
     * 图文上传
     *
     * @param fileBytes
     * @param originalFilename
     * @param loginUser
     * @param text             图文描述
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage addImageUrl(byte[] fileBytes, String originalFilename, UserInfo loginUser, String text, Integer id) {
        //   获取access_token
        String access_token = getAccess_token();
        if (access_token == null || access_token.isEmpty()) {
            log.warn("上传图片 userId:{} 获取access_token失败!!!!", loginUser.getId());
            return ResultMessage.createFail("请稍后再试!!!");
        }
        UploadimgResult result = MediaAPI.mediaUploadimg(access_token, new ByteArrayInputStream(fileBytes));
        if (result == null || StringUtils.isBlank(result.getUrl())) {
            log.warn("上传图片 userId:{} 上传失败!!!!", loginUser.getId());
            return ResultMessage.createFail("上传失败请检查文件大小,或请稍后再试!!!");
        }
        CpnActivityInfo info = new CpnActivityInfo();
        info.setId(id);
        info.setText(text);
        info.setImage_url(result.getUrl());
        info.setUpdatedBy(loginUser.getId());
        this.cpnActivityInfoDao.updateImageUrl(info);
        HashMap<String, String> map = new HashMap<>();
        map.put("image_url", result.getUrl());
        return ResultMessage.createSuccess(map);
    }

    /**
     * 开启活动  关闭活动
     *
     * @param loginUser
     * @param cpnActivityInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage openAndCloseActivity(UserInfo loginUser, CpnActivityInfo cpnActivityInfo) {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTime.format(formatter);

        CpnMchInfo cpnMchInfo = new CpnMchInfo();
        cpnMchInfo.setUserId(loginUser.getId());
        CpnMchInfo mchInfo = cpnMchInfoDao.queryCpnMchInfo(cpnMchInfo);  //得到商户merchant_id

        CpnMchServiceInfo cpnMchServiceInfo = new CpnMchServiceInfo();
        cpnMchServiceInfo.setUserId(loginUser.getId());
        CpnMchServiceInfo mchServiceInfo = cpnMchServiceInfoDao.queryCpnMchServiceInfo(cpnMchServiceInfo); //得到商家服务费率service_fee

        CpnOpenMch cpnOpenMch = cpnOpenMchDao.getByMchUserId(loginUser.getId());//得到当前商家的信息
        if (cpnOpenMch == null) {  //没有则添加信息
            cpnOpenMch = new CpnOpenMch();
            cpnOpenMch.setOemId(loginUser.getOemId());
            cpnOpenMch.setMch_user_id(loginUser.getId());
            cpnOpenMch.setMerchant_id(mchInfo.getMerchant_id());
            cpnOpenMch.setService_fee(mchServiceInfo.getService_fee());
            cpnOpenMch.setCreatedBy(loginUser.getId());
            cpnOpenMch.setUpdatedBy(loginUser.getId());
            cpnOpenMchDao.insert(cpnOpenMch);
        }


        CpnCardInfo cardInfo = new CpnCardInfo();
        cardInfo.setUserId(loginUser.getId());
        cardInfo.setActivityId(cpnActivityInfo.getId());
        cardInfo.setState(1);
        List<CpnCardInfo> cpnCardInfoList = cpnActivityInfoDao.queryActivityCard(cardInfo);

        if(cpnCardInfoList.size()>0){
            if (cpnActivityInfo.getState() == 1) {
                cpnActivityInfo.setOpenTime(format);  //设置开启时间
            } else {
                cpnActivityInfo.setCloseTime(format); //设置关闭时间
            }
            cpnActivityInfoDao.updateActivityState(cpnActivityInfo);
            return ResultMessage.createSuccess("活动开启成功!");
        }else{
            return ResultMessage.createSuccess("改活动下没有上线的优惠券");

        }


//        for (CpnCardInfo card : cpnCardInfoList) {
//            if (cpnActivityInfo.getState() == 1) {
//
//                //活动开启，优惠券上线
////                card.setState(1);
////                card.setUpdatedBy(loginUser.getId());
////                cpnCardInfoDao.updateCardState(card);
//                log.info("活动id:" + cpnActivityInfo.getId() + "成功开启，优惠券id:" + card.getId() + "成功上线");
//            } else {
//                //活动关闭，优惠券下线
//                card.setState(-1);
//                card.setUpdatedBy(loginUser.getId());
//                cpnCardInfoDao.updateCardState(card);
//                log.info("活动id:" + cpnActivityInfo.getId() + "成功关闭，优惠券id:" + card.getId() + "成功下线");
//            }
//        }


    }
}
